package com.example.admin.goodnews.fragment.MeiTuDaQuan;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout.LayoutParams;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.admin.goodnews.R;
import com.example.admin.goodnews.activity.GalleryActivity;
import com.example.admin.goodnews.adapter.GridViewAdapter;
import com.example.admin.goodnews.adapter.TuPianChaXunAdapter;
import com.example.admin.goodnews.entity.TuPianChaXunDataEntity;
import com.example.admin.goodnews.entity.TuPianLeiBieDataEntity;
import com.example.admin.goodnews.interfaces.RecyclerViewItemClickListener;
import com.example.admin.goodnews.interfaces.RecyclerViewItemLongClickListener;
import com.example.admin.goodnews.utils.GetCurrentTimeUtil;
import com.example.admin.goodnews.utils.HttpUtils;
import com.example.admin.goodnews.utils.NetWorkDataUrl;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * 美图大全页面
 * Created by admin on 2016/10/20.
 */

public class MeiTuDaQuanFragment extends Fragment implements RecyclerViewItemClickListener, RecyclerViewItemLongClickListener {
    private AppCompatSpinner appcompatspinner_meitu;// 下拉菜单
    private XRecyclerView xrecyclerview_meitu;// 下方加载小图的列表
    private GridView gridview_meitudaquan;// 页面上方加载图片分类的列表
    private GridViewAdapter gridViewAdapter;// 页面上方加载图片分类的列表的适配器
    private TuPianChaXunAdapter tuPianChaXunAdapter;// 页面下方加载数据的适配器
    private TuPianLeiBieDataEntity tuPianLeiBieDataEntity;// 页面上方加载图片分类的列表的数据实体类
    private Button btn;

    private List<TuPianChaXunDataEntity.ShowapiResBodyBean.PagebeanBean.ContentlistBean> datalists = new ArrayList<>();// 适配器需要的数据列表
    private List<TuPianChaXunDataEntity.ShowapiResBodyBean.PagebeanBean.ContentlistBean> templists = new ArrayList<>();// 存放临时数据的列表

    private LinearLayout linearlayout_content;
    private LinearLayoutManager linearLayoutManager;// 布局管理器
    private String time = GetCurrentTimeUtil.getCurrentTime();// 获取系统当前时间
    private int cWidth = 120;
    /**
     * 水平间距
     */
    private int hSpacing = 10;
    private int page = 1;// 页数，用于下拉刷新上拉加载
    private int type;// 图片二级分类的ID
    private List<Integer> types;// 下拉菜单中的id
    private int clickposition = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_meitudaquan, null);
        xrecyclerview_meitu = (XRecyclerView) view.findViewById(R.id.xrecyclerview_meitu);
        appcompatspinner_meitu = (AppCompatSpinner) view.findViewById(R.id.appcompatspinner_meitu);
        gridview_meitudaquan = (GridView) view.findViewById(R.id.gridview_meitudaquan);
        linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        xrecyclerview_meitu.setLayoutManager(linearLayoutManager);// 设置布局管理器

        btn = (Button) view.findViewById(R.id.btn);

        // 下拉刷新和上拉加载
        xrecyclerview_meitu.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getData();
            }

            @Override
            public void onLoadMore() {
                page++;
                getData();
            }
        });
        getTuPianLeiBie();
        getData();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 图片分类GridView的点击事件
        gridview_meitudaquan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 记录图片大分类的点击位置
                clickposition = position;
                // 获取下拉框中的数据
                List<TuPianLeiBieDataEntity.ShowapiResBodyBean.ListsBean.ListBean> list = new ArrayList<>();
                List<String> spinnerlist = new ArrayList<>();// 下拉菜单中的name
                types = new ArrayList<Integer>();// 下拉菜单中的ID
                list = tuPianLeiBieDataEntity.getShowapi_res_body().getLists().get(position).getList();
                for (int j = 0; j < list.size(); j++) {
                    spinnerlist.add(list.get(j).getName());
                    types.add(list.get(j).getId());
                }
                ArrayAdapter<String> arrayadapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, spinnerlist);
                appcompatspinner_meitu.setAdapter(arrayadapter);
                arrayadapter.notifyDataSetChanged();
            }
        });
        // 下拉菜单点击事件
        appcompatspinner_meitu.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                type = tuPianLeiBieDataEntity.getShowapi_res_body().getLists().get(clickposition).getList().get(position).getId();
                getData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), GalleryActivity.class);
                startActivity(intent);
            }
        });

    }

    // 获取图片类别
    private void getTuPianLeiBie() {
        String param = NetWorkDataUrl.TUPIANLEIBIE_PARAM1 + time + NetWorkDataUrl.TUPIANLEIBIE_PARAM2;
        try {
            HttpUtils.doPostAsyn(NetWorkDataUrl.TUPIANLEIBIE_URL, param, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    tuPianLeiBieDataEntity = gson.fromJson(result, TuPianLeiBieDataEntity.class);
                    if (tuPianLeiBieDataEntity.getShowapi_res_body().getLists().size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //  获取图片二级分类
    private void getData() {
        String param = NetWorkDataUrl.TUPIANCHAXUN_PARAM1 + page + NetWorkDataUrl.TUPIANCHAXUN_PARAM2 + time + NetWorkDataUrl.TUPIANCHAXUN_PARAM3 + type + NetWorkDataUrl.TUPIANCHAXUN_PARAM4;
        try {
            HttpUtils.doPostAsyn(NetWorkDataUrl.TUPIANCHAXUN_URL, param, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    templists = gson.fromJson(result, TuPianChaXunDataEntity.class).getShowapi_res_body().getPagebean().getContentlist();
                    if (templists.size() > 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void singleGridView(int size) {
        // 设置GridView单行显示
        int length = 100;
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 4) * density);
        int itemWidth = (int) (length * density);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.MATCH_PARENT);
        gridview_meitudaquan.setLayoutParams(params); // 设置GirdView布局参数,横向布局的关键
        gridview_meitudaquan.setColumnWidth(itemWidth); // 设置列表项宽
        gridview_meitudaquan.setHorizontalSpacing(5); // 设置列表项水平间距
        gridview_meitudaquan.setStretchMode(GridView.NO_STRETCH);
        gridview_meitudaquan.setNumColumns(size); // 设置列数量=列表集合数
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(getActivity(), "数据为空~", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    // 图片大分类
                    int size = tuPianLeiBieDataEntity.getShowapi_res_body().getLists().size();
                    singleGridView(size);// 设置GridView单行显示
                    gridViewAdapter = new GridViewAdapter(getActivity(), tuPianLeiBieDataEntity);
                    gridview_meitudaquan.setAdapter(gridViewAdapter);

                    // 解决第一次打开页面时下拉菜单中没有数据的问题
                    List<TuPianLeiBieDataEntity.ShowapiResBodyBean.ListsBean> lists = tuPianLeiBieDataEntity.getShowapi_res_body().getLists();
                    List<TuPianLeiBieDataEntity.ShowapiResBodyBean.ListsBean.ListBean> list = lists.get(0).getList();
                    List<String> spinnerlist = new ArrayList<>();
                    for (int j = 0; j < list.size(); j++) {
                        spinnerlist.add(list.get(j).getName());
                    }
                    ArrayAdapter<String> arrayadapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, spinnerlist);
                    appcompatspinner_meitu.setAdapter(arrayadapter);
                    arrayadapter.notifyDataSetChanged();
                    break;
                case 2:
                    if (page == 1) {
                        datalists.clear();
                        datalists.addAll(templists);
                        tuPianChaXunAdapter = new TuPianChaXunAdapter(getActivity(), datalists);// 初始化适配器
                        xrecyclerview_meitu.setAdapter(tuPianChaXunAdapter);// 给RecyclerView设置适配器
                        xrecyclerview_meitu.refreshComplete();
                        templists.clear();
                    } else {
                        datalists.addAll(templists);
                        tuPianChaXunAdapter.notifyDataSetChanged();
                        xrecyclerview_meitu.loadMoreComplete();
                        templists.clear();
                    }
                    tuPianChaXunAdapter.setRecyclerViewItemClickListener(MeiTuDaQuanFragment.this);
                    tuPianChaXunAdapter.setRecyclerViewItemLongClickListener(MeiTuDaQuanFragment.this);
                    break;
            }
        }
    };

    @Override
    public void RecyclerViewItemClickListener(int position) {
        ArrayList<String> gallerylist = new ArrayList<>();
        for (int i = 0; i < templists.size(); i++) {
            gallerylist.add(templists.get(position).getList().get(i).getMiddle());
        }
        Intent intent = new Intent(getActivity(), GalleryActivity.class);
//        Bundle bundle = new Bundle();
//        bundle.putStringArrayList("gallerylist", gallerylist);
//        intent.putExtra("gallery", bundle);
        intent.putStringArrayListExtra("gallerylist", gallerylist);
        startActivity(intent);
    }

    @Override
    public void RecyclerViewItemLongClickListener(int position) {
        ArrayList<String> gallerylist = new ArrayList<>();
        for (int i = 0; i < templists.size(); i++) {
            gallerylist.add(templists.get(position).getList().get(i).getMiddle());
        }
        Intent intent = new Intent(getActivity(), GalleryActivity.class);
//        Bundle bundle = new Bundle();
//        bundle.putStringArrayList("gallerylist", gallerylist);
//        intent.putExtra("gallery", bundle);
        intent.putStringArrayListExtra("gallerylist", gallerylist);
        startActivity(intent);
    }
}
